<template>
	<div class="system-user-container layout-padding">
		<el-card shadow="hover" class="layout-padding-auto">
			<div class="system-user-search mb15">
	
        <div class="button_poastion_flex_iem">
                            <el-button
                              size="default"
                              type="primary"
                              class="dr2333"
                             
                              @click="addNEWproUser"
                              >关联系统角色</el-button
                            >
                          
                          </div>
			</div>
	
                          <el-table
                          v-loading='loadingTable'
                          size="default"
                            :data="userTable"
                            class="roledata"
                          
                            height="700"
                          >
                           
                            <el-table-column prop="user_role" label="角色名称">
                              <!-- <template #header>
                              <div class="filter_item">
                                <span>主项号</span>
                                <filterCom :options="allproSubcode" @chooseItem="chooseproSubcode"></filterCom>
                              </div>
                            </template> -->
                            </el-table-column>
                            <el-table-column prop="user_account" label="用户名">

                              <template #default="scope">
                               
                               <el-tag style="margin-right: 5px;margin-bottom: 5px;" size="small" v-for="(item, index) in scope.row.person" :key="index" type='danger'>
                               {{ item.user_account }}
                               </el-tag>
                           </template>
                            </el-table-column>
                            <el-table-column prop="user_name" label="人员名称">
                              <template #default="scope">
                               
                                <el-tag style="margin-right: 5px;margin-bottom: 5px;" size="small" v-for="(item, index) in scope.row.person" :key="index" type='success'>
                                {{ item.user_name }}
                                </el-tag>
                            </template>
                            </el-table-column>
                           
                            <el-table-column width="150" label="操作">
                              <template #default="scope">
                                <span
                               
                                  style="
                                    color: #1890ff;
                                    margin-right: 1em;
                                    cursor: pointer;
                                    font-size: 12px;
                                  "
                                  size="small"
                                  @click="handleEdit2User(scope.$index, scope.row)"
                                >
                                  编辑
                                </span>
                                <el-popconfirm
                                  title="确定要删除吗?"
                                  @confirm="
                                    confirmEvent2User(scope.$index, scope.row)
                                  "
                                >
                                  <template #reference>
                                    <span
                                      style="
                                        color: #f56c6c;
                                        cursor: pointer;
                                        font-size: 12px;
                                      "
                                      >删除</span
                                    >
                                  </template>
                                </el-popconfirm>
                              </template>
                            </el-table-column>
                          </el-table>
		</el-card>
		<UserDialog ref="userDialogRef" @refresh="getTableData()" />
	
  
    <el-dialog
      size="small"
      draggable
      v-model="dialogVisibleEdit3User"
      :destroy-on-close="true"
      :before-close="() => resetFormEdit3User(ruleFormRefEdit3User)"
      title="新增系统角色"
      width="25%"
    >
      <el-form
        size="default"
        ref="ruleFormRefEdit3User"
        :model="ruleFormEdit3User"
        :rules="rulesNew2User"
        label-width="100px"
        class="demo-ruleForm-Edit"
        
      >
        <el-form-item label="角色名称：" prop="role_name">
          <el-select  clearable style="width: 100%" size="default" filterable placeholder="请选择角色名称" v-model="ruleFormEdit3User.role_name">
            <el-option
            v-for="(item,index) in roleOptions" :key="index" :label="item.label" :value="item.value"
            >

            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="参与人员：" prop="name">
          <el-select :filter-method="matchRole" clearable multiple collapse-tags collapse-tags-tooltip   style="width: 100%" size="default" filterable placeholder="请选择参与人员" v-model="ruleFormEdit3User.name">
            <el-option
            v-for="(item,index) in personOptions_PINYING" :key="index" :label="item.label" :value="item.value"
            >

            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <div class="button_footer">
            <el-button
              size="default"
              type="primary"
              @click="submitFormEdit3User(ruleFormRefEdit3User)"
              >新增</el-button
            >
           
            <el-button size="default" @click="resetFormEdit3User(ruleFormRefEdit3User)"
              >取消</el-button
            >
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>


    <el-dialog
      size="default"
      draggable
      v-model="dialogVisibleEditUser"
      :destroy-on-close="true"
      :before-close="() => resetFormEdit3Users(ruleFormRefEdit3Users)"
      title="编辑用户"
      width="23%"
    >
      <el-form
        size="default"
        ref="ruleFormRefEdit3Users"
        :model="ruleFormEditUser"
        :rules="rulesNew2User"
        label-width="100px"
        class="demo-ruleForm-Edit"
        
      >
        <el-form-item label="角色名称：" prop="role_name">
          <el-select   disabled style="width: 100%" size="small" filterable placeholder="请选择角色名称" v-model="ruleFormEditUser.role_name">
            <el-option
            v-for="(item,index) in roleOptions" :key="index" :label="item.label" :value="item.value"
            >

            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="参与人员：" prop="name">
        
          <el-select :filter-method="matchRole" clearable multiple  collapse-tags collapse-tags-tooltip   style="width: 100%" size="small" filterable placeholder="请选择参与人员" v-model="ruleFormEditUser.name">
            <el-option
            v-for="(item,index) in personOptions_PINYING" :key="index" :label="item.label" :value="item.value"
            >

            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <div class="button_footer">
            <el-button
              size="default"
              type="primary"
              @click="submitFormEdit3Users(ruleFormRefEdit3Users)"
              >确认</el-button
            >
       
            <el-button size="default" @click="resetFormEdit3Users(ruleFormRefEdit3Users)"
              >取消</el-button
            >
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>


 


</template>

<script setup name="systemUser">
import PinYinMatch from "pinyin-match";
import { defineAsyncComponent, reactive, onMounted, ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import {
  
  AddProjectUserV2,
 
  GetProjectUsers,
  GetDepartmentUsersV2,
  GetRoles,
  DeleteUserV2

} from "../../../api/projectManage/projectList";
// 引入组件
const UserDialog = defineAsyncComponent(() => import('/@/views/system/user/dialog.vue'));

let ruleFormRefEdit3Users = ref('')

let resetFormEdit3Users = (formEl) => {
  if (!formEl) return;
  dialogVisibleEditUser.value = false;
  formEl.resetFields();
};



let matchRole = (searchContent) => {
  if (searchContent) {
    let result = [];
    personOptions_PINYING.value.forEach((item) => {
      // matchResult 的值为 true/false
      let matchResult = PinYinMatch.match(item.label, searchContent);
      if (matchResult) {
        result.push(item);
      }
    });
 
    personOptions_PINYING.value = result;
    console.log(result)
  } else {
    personOptions_PINYING.value = personOptions.value;
  }
};


let confirmEvent2User = async(index,row) => {
  ElMessageBox.confirm(`此操作将永久删除，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async() => {
      row.person.forEach(async (v)=>{
        await DeleteUserV2({
        user_oid: v.user_oid,
      });
      })
      
			 setTimeout(()=>{
        getUserAllData()
			ElMessage.success('删除成功');
       },1000)
		})
}

let submitFormEdit3Users = async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid) => {
    if (valid) {
      let resRole = await GetRoles()
  let resPerson = await GetDepartmentUsersV2({dept:'equipment'})
  let user_permission = resRole.filter(v=>v.role_name ==ruleFormEditUser.value.role_name)[0].role_auth_code
   let users =ruleFormEditUser.value.name.map(v=>{

    return {
      ...resPerson.find(item => item.user_name === v),
      user_permission:user_permission,
      user_account:resPerson.find(item => item.user_name === v).login_account,
    };
  })



      let obj = {
    "proj_oid": '',
    "user_role": ruleFormEditUser.value.role_name,
    "users": users
};



      await AddProjectUserV2(obj);
      ElMessage({
        message: "修改成功",
        type: "success",
      });
      getUserAllData()
      dialogVisibleEditUser.value = false;
    }
  });
};

let ruleFormEditUser = ref({})
let dialogVisibleEditUser = ref(false)
let personOptions_PINYING = ref([])
let handleEdit2User = async(index, item) => {
  let resRole = await GetRoles()
  let resPerson = await GetDepartmentUsersV2({dept:'equipment'})
  
  personOptions.value = resPerson.map(v=>{
  return {
    value:v.user_name,
    label:v.user_name
  }
  }
  )
  roleOptions.value = resRole.filter(v=>v.role_auth_code<=40).map(v=>{
    return {
      value:v.role_name,
      label:v.role_name
    }
  }).reverse()
  personOptions_PINYING.value = personOptions.value
  dialogVisibleEditUser.value = true;

  ruleFormEditUser.value = { ...item
  ,role_name:item.user_role,
  name:item.person.map(v=>v.user_name),
  };
  


};


let rulesNew2User = ref({
  role_name: [{ required: true, message: "请选择角色名称", trigger: "change" }],
  name: [{ required: true, message: "请选择人员", trigger: "change" }],
});

let ruleFormRefEdit3User = ref('')
let resetFormEdit3User = (formEl) => {
  console.log(formEl)
  if (!formEl) return;
  dialogVisibleEdit3User.value = false;
  formEl.resetFields();
};

let ruleFormEdit3User= ref({
  role_name:'',
  name:[],
})
let submitFormEdit3User = async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid) => {
    if (valid) {
      let resRole = await GetRoles()
  let resPerson = await GetDepartmentUsersV2({dept:'equipment'})
  let user_permission = resRole.filter(v=>v.role_name ==ruleFormEdit3User.value.role_name)[0].role_auth_code
  let users = ruleFormEdit3User.value.name.map(v=>{

    return {
      ...resPerson.find(item => item.account_id === v),
      user_permission:user_permission,
      user_account:resPerson.find(item => item.account_id === v).login_account,
    };
  })



      let obj = {
    "proj_oid":'',
    "user_role": ruleFormEdit3User.value.role_name,
    "users": users
};



      await AddProjectUserV2(obj);
      ElMessage({
        message: "新增成功",
        type: "success",
      });
      ruleFormRefEdit3User.value.resetFields();
      dialogVisibleEdit3User.value = false;
      getUserAllData()
    
    }
  });
};

let loadingTable = ref(true)

let userTable = ref([])
let getUserAllData = async() => {
  let res = await GetRoles()
  let obj = {}
 

  for (let  i in res){
    let result = await GetProjectUsers({ proj_oid: '',user_role:res[i].role_name})
    if(result.length > 0){
      obj[`${res[i].role_name}`] = result
    }
  
  }
  let arr = []
  Object.entries(obj).forEach(([key,value]) => {
      arr.push({
        user_role:key,      
        person:value
      })
  })

  userTable.value = arr
 

}

let personOptions = ref([])
let roleOptions = ref([])
let dialogVisibleEdit3User =ref(false)
let addNEWproUser = async() => {

let resRole = await GetRoles()
let resPerson = await GetDepartmentUsersV2({dept:'equipment'})
personOptions.value = resPerson.map(v=>{
return {
  value:v.account_id,
  label:v.user_name
}
}
)

roleOptions.value = resRole.filter(v=>Number(v.role_auth_code)>60).map(v=>{
  return {
    value:v.role_name,
    label:v.role_name
  }
}).reverse()
personOptions_PINYING.value = personOptions.value
let flag = []
if(userTable.value.length>0){
  roleOptions.value.forEach(v=>{

flag =  flag.concat(userTable.value.filter(item=>item.user_role==v.value))
  })
  let flagMap = flag.map(v=>v.user_role)


 flagMap.forEach(v=>{
    roleOptions.value.forEach((item,index)=>{
      if(item.value ==  v){
        roleOptions.value.splice(index,1)
      }
    })
  })

}

dialogVisibleEdit3User.value = true;
};


// 定义变量内容
const userDialogRef = ref();
const state = reactive({
	tableData: {
		data: [],
		total: 0,
		loading: false,
		param: {
			pageNum: 1,
			pageSize: 10,
		},
	},
});

// 初始化表格数据
const getTableData = () => {
	state.tableData.loading = true;
	const data = [];
	for (let i = 0; i < 2; i++) {
		data.push({
			userName: i === 0 ? 'admin' : 'test',
			userNickname: i === 0 ? '我是管理员' : '我是普通用户',
			roleSign: i === 0 ? 'admin' : 'common',
			department: i === 0 ? ['vueNextAdmin', 'IT外包服务'] : ['vueNextAdmin', '资本控股'],
			phone: '12345678910',
			email: 'vueNextAdmin@123.com',
			sex: '女',
			password: '123456',
			overdueTime: new Date(),
			status: true,
			describe: i === 0 ? '不可删除' : '测试用户',
			createTime: new Date().toLocaleString(),
		});
	}
	state.tableData.data = data;
	state.tableData.total = state.tableData.data.length;
	setTimeout(() => {
		state.tableData.loading = false;
	}, 500);
};
// 打开新增用户弹窗
const onOpenAddUser = (type) => {
	userDialogRef.value.openDialog(type);
};
// 打开修改用户弹窗
const onOpenEditUser = (type, row) => {
	userDialogRef.value.openDialog(type, row);
};
// 删除用户
const onRowDel = (row) => {
	ElMessageBox.confirm(`此操作将永久删除账户名称：“${row.userName}”，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			getTableData();
			ElMessage.success('删除成功');
		})
		.catch(() => {});
};
// 分页改变
const onHandleSizeChange = (val) => {
	state.tableData.param.pageSize = val;
	getTableData();
};
// 分页改变
const onHandleCurrentChange = (val) => {
	state.tableData.param.pageNum = val;
	getTableData();
};
// 页面加载时
onMounted(async() => {
 

  setTimeout(()=>{
    loadingTable.value = false
  },1500)
	getUserAllData()
	
});
</script>

<style scoped lang="scss">
.system-user-container {
	:deep(.el-card__body) {
		display: flex;
		flex-direction: column;
		flex: 1;
		overflow: auto;
		.el-table {
			flex: 1;
		}
	}
}
</style>
